# -*- coding: UTF-8 -*-
import mqtt
import ujson
import utime as time
import _thread
import httpdown



#==========================================================
#填入MQTT信息
AccessToken = "**********"
ProjectKey = "********"
mqttaddr = "sh-1-mqtt.iot-api.com"
serverport = 1883
#==========================================================

#版本属性
version_info = {
    'version' : '1.0.0' ,
    }
url=''
size=0
version=''
upgrade=False
mqtt_state = 0
#服务质量
qos = 1

#topic
_get_send = "command/send/+"    #设备接收云端下发命令需要订阅此主题
_update_topic = "attributes"  #属性上报用于向云端上报版本信息等属性


# 定义subcribe的回调函数，接收OTA下发的命令
def on_subcribe(topic,payload):
    global client,url,size,version,upgrade
    #平台下发的命令
    cloudmsg = ujson.loads(payload)
    params=cloudmsg['params']
    print('params',params)
    upgrade = params['upgrade']  #升级状态，是否升级
    md5 = params['md5']
    size = params['size']   #升级文件大小
    url = params['url']   #升级文件的下载url
    version = params['version']    #下载的文件版本
    

def mqttloop_func(delay, id):
    global client
    global mqtt_state
    while True:
        time.sleep_ms(delay)
        # print('Running thread %d'%id)
        ret = client.loop(1000)
        # print('client ret ={}'.format(ret))
        if ret < 0:
            print('------------------mqtt disconnect!')
            mqtt_state = 0
            client.disconnect()
            mqtt_reconnect()
        else:
            pass

#获取mqtt连接状态
def get_mqtt_state():
    global mqtt_state
    return mqtt_state


def mqtt_reconnect():
    global client
    global mqtt_state
    global update_topic
    clientId = "TestRTU"       #可填写任意名称
    hearttime = 40
    #订阅/发布的topic
    get_send = _get_send
    update_topic = _update_topic

    client = mqtt.client(clientId)
    client.on_subcribe(on_subcribe)

    # 设置用户名和密码
    client.username_pw_set(AccessToken,ProjectKey)
    # 建立mqtt连接
    ret = client.connect(mqttaddr,serverport,hearttime)
    if ret == 0:
        mqtt_state = 1
    # 订阅命令
    client.subscribe(get_send,qos)

    # 上报版本属性
    update(version_info)

def mqtt_connect():
    mqtt_reconnect()
    #创建mqtt接收数据任务，1s一次
    _thread.start_new_thread(mqttloop_func,(1000, 1))


#上报属性
def update(send_data):
    global client
    MSG = ujson.dumps(send_data)
    print(MSG)
    client.publish(update_topic,MSG,qos)
    
#云端下发命令后执行下载
def http_ota():
    global url,size,version,upgrade
    if upgrade:
        print('''
              upgrade:{},
              size:{},
              version:{},
              url:{}'''.format(upgrade,size,version,url))
        upgrade = False
        httpdown.ota_py_app(url)
        